<!--
 * @Author: ybf
 * @Date: 2023-02-21 15:31:51
 * @LastEditTime: 2023-12-15 16:31:13
 * @Description: 描述
 * Copyright (c) 2023 by 慧能分享, All Rights Reserved.
-->
<template>
  <div class="measurationInfoSheet">
    <!-- <nu-col :span="24" style="height:calc(170px - 20px);"> -->
    <!-- <nutbTitle title="量测信息表"></nutbTitle> -->
    <div class="radioStyle">
      <span class="label">通道组</span>
      <nu-select :list="channelGroupObject" style="width: 206px" v-model="formData.channel" :valueName="'id'"
        :label="'groupName'" @change="channelChange" placeholder="请选择"></nu-select>
      <el-radio-group class="el_radioView" v-model="formData.mesaType" @input="relatedNameInput"
        style="margin-left: 63px">
        <!-- 选项 -->
        <el-radio-button v-for="item in measureTypeList" :key="item.dictActualValue" :label="item.dictActualValue">
          {{ item.dictName }}
        </el-radio-button>
      </el-radio-group>
    </div>
    <div class="line"></div>
    <!-- <nu-radioButton :group="measureTypeList.dictName" :name="measureTypeList.dictName"  ></nu-radioButton> -->
    <NuVerifyForm :model="formData" ref="formData" label-width="130px" class="searchForm" @searchForm="searchForm"
      :buttons="fyButtons">
      <NuformItem label="关联对象名称" prop="devName" width="auto">
        <nu-input type="text" v-model="formData.devName" size="middle" placeholder="请输入关联对象名称"></nu-input>
      </NuformItem>
      <NuformItem label="量测名称" prop="meterName" width="auto">
        <nu-input type="text" v-model="formData.meterName" size="middle" placeholder="请输入量测名称"></nu-input>
      </NuformItem>
      <!-- <NuformItem label="量测类型" prop="mesaType" width="auto">
                <nu-select class="searchSelect" :filterable="true" :list="measureTypeList" :valueName="'dictActualValue'"
                    :label="'dictName'" type="text" v-model="formData.mesaType" autocomplete="off"
                    @change="measureTypeChange" style="width: 100%;" placeholder="请选择">
                </nu-select>
            </NuformItem> -->
      <NuformItem label="关联类型" prop="devType" width="auto">
        <nu-select class="searchSelect" :filterable="true" :list="unitBusTypeList" :valueName="'dictActualValue'"
          :label="'dictName'" type="text" v-model="formData.devType" autocomplete="off" @change="associationTypeChange"
          style="width: 100%" placeholder="请选择">
        </nu-select>
      </NuformItem>
      <div class="btnBox">
        <nu-button type="primary" class="searchButton" @click="searchTable">搜索</nu-button>
        <nu-button class="searchButton" @click="clearParams">清除</nu-button>
        <!-- <nu-button type="primary" class="searchButton" @click="importTable">导入</nu-button> -->
      </div>
    </NuVerifyForm>
    <!-- </nu-col> -->
    <div class="line"></div>
    <div style="height: 35px; position: relative; padding: 0 10px" class="renovateTime">
      <nu-button class="searchButton" @click="addTable">新增</nu-button>
      <nu-button class="searchButton" v-if="formData.mesaType != 204" @click="batchAddTable">批量新增</nu-button>
      <nu-button class="searchButton" @click="importTable">导入</nu-button>
      <nu-button class="searchButton" @click="exportTable">导出</nu-button>
    </div>
    <!-- <nu-col :span="24" style="height: calc(100% - 170px - 20px);"> -->
    <!-- <nutbTitle title="量测信息列表"></nutbTitle> -->
    <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSource" :options="options"
      :operates="operates(this)" :pagination="pagination" @handleSizeChange="handleSizeChange"
      @handleChangePage="handleChangePage" @handleCurrentChange="handleCurrentChange" @sortChange="sortChange">
    </NuTableList>
    <!-- </nu-col> -->
    <!-- 单点新增 -->
    <nu-dialog :title="dialogTitle" :visible.sync="dialogShow" width="750px" destroy-on-close center
      :close-on-click-modal="false" top="5vh" :modal-append-to-body="false" @close="diaClose">
      <div class="dialogHeaderSearch">
        <NuVerifyForm :model="dialogFormData" ref="dialogFormData" label-width="130px" class="submitForm"
          @submitForm="diaSubmitForm" :buttons="fyButtons">
          <!-- <NuformItem label="量测类型：" prop="relatedName" width="100%"
                        :rules="[{ required: true, message: '量测类型不能为空' }]">
                        <nu-radioButton :group="measureTypeGroup" v-model="dialogFormData.relatedName"
                            @input="related(dialogFormData.relatedName)"></nu-radioButton>
                    </NuformItem> -->
          <NuformItem label="量测点号：" prop="ioa" width="100%" :rules="[{ required: true, message: '量测点号不能为空' }]">
            <nu-input type="number" v-model="dialogFormData.ioa" size="middle" placeholder="请输入数字"
              style="width: 70%"></nu-input>
          </NuformItem>
          <NuformItem label="关联对象：" prop="relatedDevId" width="100%" :rules="[{ required: true, message: '关联对象不能为空' }]">
            <div style="display: flex; flex-direction: row">
              <nu-select class="searchSelect" :filterable="true" :list="unitBusTypeList" :valueName="'dictActualValue'"
                :label="'dictName'" type="text" v-model="dialogFormData.relatedDevType" autocomplete="off"
                @change="unitBusTypeChange" style="width: 35%" placeholder="请选择">
              </nu-select>
              <nu-select class="searchSelect" :filterable="true" @change="searchSelectChange"
                :list="setRelatedDevType(dialogFormData.relatedDevType)" type="text" v-model="dialogFormData.relatedDevId"
                autocomplete="off" :valueName="setValueName(dialogFormData.relatedDevType)"
                :label="setlableList(dialogFormData.relatedDevType)" style="width: calc(36.5% - 9px)"
                :disabled="dialogFormDisabled" placeholder="请选择">
              </nu-select>
            </div>
          </NuformItem>
          <NuformItem label="对应量测名称：" prop="meterName" width="100%" :rules="[{ required: true, message: '对应量测名称不能为空' }]">
            <el-autocomplete v-model="dialogFormData.meterName" :fetch-suggestions="querySearchAsync" placeholder="请选择"
              @select="handleSelect" style="width: 70%">
              <template slot-scope="{ item }">
                <div class="name">{{ item.dictName }}</div>
              </template>
            </el-autocomplete>
          </NuformItem>
          <NuformItem label="单位：" prop="unit" :rules="[{ required: requiredFunc, message: '单位不能为空' }]"
            v-if="isMeasureType">
            <nu-select class="searchSelect" clearable :filterable="true" :list="unitList" type="text"
              :valueName="'dictName'" :label="'dictName'" v-model="dialogFormData.unit" autocomplete="off"
              style="width: calc(100% - 5px); margin-left: 2px" :disabled="dialogFormDisabled" placeholder="请选择">
            </nu-select>
          </NuformItem>
          <NuformItem label="系数：" prop="coeff" :rules="[{ required: requiredFunc, message: '系数不能为空' }]"
            v-if="isMeasureType">
            <nu-input type="number" v-model="dialogFormData.coeff" size="middle" :disabled="dialogFormDisabled" @input="(value) => {
              if (value.indexOf('.') > 0) {
                dialogFormData.coeff = value.slice(
                  0,
                  value.indexOf('.') + 11
                );
              }
            }
              " @blur="coefBlur($event, 2)" placeholder="请输入数字"></nu-input>
          </NuformItem>
          <NuformItem label="偏移量：" prop="offsetVal" :rules="[{ required: requiredFunc, message: '偏移量不能为空' }]"
            v-if="isMeasureType">
            <nu-input type="number" v-model="dialogFormData.offsetVal" size="middle" :disabled="dialogFormDisabled"
              placeholder="请输入数字"></nu-input>
          </NuformItem>
          <NuformItem label="上限：" prop="upperLimit" :rules="[{ required: false, message: '上限不能为空' }]"
            v-if="isMeasureType">
            <nu-input type="number" v-model="dialogFormData.upperLimit" size="middle" :disabled="dialogFormDisabled"
              placeholder="请输入数字"></nu-input>
          </NuformItem>
          <NuformItem label="下限：" prop="lowerLimit" :rules="[{ required: false, message: '下限不能为空' }]"
            v-if="isMeasureType">
            <nu-input type="number" v-model="dialogFormData.lowerLimit" size="middle" :disabled="dialogFormDisabled"
              placeholder="请输入数字"></nu-input>
          </NuformItem>
          <NuformItem label="PT变比：" prop="pt" :rules="[{ required: false, message: 'PT变比不能为空' }]"
            v-if="isSysEnergyType && requiredFunc">
            <nu-input type="number" v-model="dialogFormData.pt" size="middle" :disabled="dialogFormDisabled"
              placeholder="请输入数字"></nu-input>
          </NuformItem>
          <NuformItem label="CT变比：" prop="ct" :rules="[{ required: false, message: 'CT变比不能为空' }]"
            v-if="isSysEnergyType && requiredFunc">
            <nu-input type="number" v-model="dialogFormData.ct" size="middle" :disabled="dialogFormDisabled"
              placeholder="请输入数字"></nu-input>
          </NuformItem>
          <NuformItem label="量测值字典：" prop="meterValueDesc" :rules="[{ required: false, message: '量测值字典不能为空' }]"
            v-if="isSysEnergyType && requiredFunc" width="100%">
            <nu-input type="textarea" :rows="2" v-model="dialogFormData.meterValueDesc" size="middle"
              :disabled="dialogFormDisabled" placeholder="请输入量测值字典" style="width: calc(100% - 5px);"></nu-input>
          </NuformItem>
        </NuVerifyForm>
        <nu-button class="dialogSearchButton" type="primary" @click="diaClose">取消</nu-button>
        <nu-button class="dialogSearchButton" type="primary" @click="diaSave" v-if="dialogTitle == '编辑'">确定</nu-button>
        <nu-button class="dialogSearchButton" type="primary" @click="diaSave" v-if="dialogTitle == '新增'">确定</nu-button>
      </div>
    </nu-dialog>
    <!-- 批量新增 -->
    <nu-dialog :title="dialogBatchTitle" :visible.sync="dialogBatchShow" width="70%" center :close-on-click-modal="false"
      top="5vh" :modal-append-to-body="false" @close="diaBatchClose" destroy-on-close>
      <div class="dialogHeaderSearch batch">
        <NuTableList :showFilter="false" :columns="batchColumns" :dataSource="batchDataSource" style="width: 100%"
          :options="options">
        </NuTableList>
        <nu-button class="dialogSearchButton" type="primary" @click="diaBatchSave">保存</nu-button>
      </div>
    </nu-dialog>
    <!-- 导入 -->
    <nu-dialog :title="upload.title" :visible.sync="upload.open" width="30%" center :close-on-click-modal="false"
      top="5vh" :modal-append-to-body="false" append-to-body @close="closeFileForm">
      <div class="upload_des">
        <span>请下载模板文件，并根据模板中的样式要求，填写信息</span>
        <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
          @click="importTemplate">导入模板.xlsx</el-link>
      </div>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :on-change="handleChange" :auto-upload="false" drag :data="upload.data" name="file" :file-list="upload.fileList">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>1.后缀为xls或xlsx；</span>
          <span>2.文件大小不超过5M；</span>
          <span>3.若有多个sheet页，默认读取第一个</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="closeFileForm">取 消</el-button>
      </div>
    </nu-dialog>
  </div>
</template>
    
<script>
import nuCol from "@/components/base/col.vue";
import nutbTitle from "@/components/base/tableTitle.vue";
import NuVerifyForm from "@/components/verify-form";
import NuformItem from "@/components/verify-form/form-item.vue";
import nuInput from "@/components/base/input";
import nuSelect from "@/components/base/select";
import nuButton from "@/components/base/button";
import NuTableList from "@/components/tableList/TableFormList";
import nuDialog from "@/components/base/dialog";
import nuRadio from "@/components/base/radio";
import nuRadioButton from "@/components/base/radio-button";
import axios from "axios";
const operates = (that) => [
  {
    label: "编辑",
    icon: "",
    width: "50px",
    isShow: (row) => {
      return true;
    },
    disabled: (row) => {
      return false;
    },
    method: (row) => {
      that.openEdit(row);
    },
  },
  // {
  //   isShow: row => {
  //     return false;
  //   },
  // },
  {
    label: "删除",
    icon: "",
    width: "50px",
    isShow: (row) => {
      return true;
    },
    disabled: (row) => {
      return false;
    },
    method: (row) => {
      that.tbRowdetele(row);
    },
  },
];
import { getToken } from "@/utils/auth";
import store from "@/store";
export default {
  name: "measurationInfoSheet",
  components: {
    nuCol,
    nutbTitle,
    NuVerifyForm,
    NuformItem,
    nuInput,
    nuSelect,
    nuButton,
    NuTableList,
    nuDialog,
    nuRadio,
    nuRadioButton,
  },
  data() {
    return {
      formData: {
        channel: "",
        associationType: "",
        mesaType: 201,
        devName: "",
        devType: "",
        meterName: "",
      },
      channelGroupObject: [],
      nitBusTypeDict: [], // 关联类型
      nitBusTypeId: "301",
      dialogFormData: {
        relatedDevName: "",
        unitBusType: "关联机组",
        meterName: "",
        unitBusName: "",
        mesaType: 201,
        channelGroupId: "",
        channelGroupName: "",
        upperLimit: "",
        lowerLimit: "",
        coeff: "",
        unit: "MW",
        ioa: "",
        relatedName: "遥测",
        relatedDevId: "",
        relatedDevType: "",
        offsetVal: "",
        pt: "",
        ct: "",
        meterValueDesc: ""
        // relatedDevType:
      },
      fyButtons: [],
      operates,
      currentRow: null,
      pagination: {
        pageSize: 20,
        total: 0,
        pageNum: 1,
        currentPage: 1,
      },
      dialogTitle: "",
      dialogShow: false,
      dialogBatchTitle: "",
      dialogBatchShow: false,
      measureTypeGroup: ["遥测", "遥信", "遥调"],
      unitBusTypeGroup: ["关联机组", "关联母线"],
      measureTypeList: [],
      unitBusTypeList: [
        { label: "关联机组", value: 1 },
        { label: "关联母线", value: 2 },
      ],
      unitList: [
        { label: "kW", value: 1 },
        { label: "MW", value: 2 },
        { label: "W", value: 3 },
        { label: "kV", value: 4 },
      ],
      busNameList: [{ label: "母线1", value: 1 }],
      unitNameList: [{ label: "机组1", value: 1 }],
      lineList: [{ label: "机组1", value: 1 }],
      transformerList: [{ label: "机组1", value: 1 }],

      ioaOrder: "asc",
      channelGroup: [],
      radioObj: false,
      columns: [
        {
          label: "序号",
          prop: "ranking",
          width: "70px",
          render: (h, params) => {
            if (this.pagination) {
              return h(
                "span",
                params.index +
                1 +
                (this.pagination.pageNum - 1) * this.pagination.pageSize
              );
            }
          },
        },
        {
          label: "对应量测名称",
          prop: "meterName",
        },
        {
          label: "量测点号",
          prop: "ioa",
          sortable: true,
          // sortMethod: (a, b) => {
          //   return a.ioa - b.ioa
          // },
          sortOrders: ['descending', 'ascending'],

        },
        {
          label: "系数",
          prop: "coeff",
          isShow: (row) => {
            if (
              this.formData.mesaType == "202" ||
              this.formData.mesaType == "204"
            ) {
              return false;
            } else {
              return true;
            }
            //
          },
        },
        {
          label: "单位",
          prop: "unit",
          isShow: (row) => {
            if (
              this.formData.mesaType == "202" ||
              this.formData.mesaType == "204"
            ) {
              return false;
            } else {
              return true;
            }
            //
          },
        },
        {
          label: "偏移量",
          prop: "offsetVal",
          isShow: (row) => {
            if (
              this.formData.mesaType == "202" ||
              this.formData.mesaType == "204"
            ) {
              return false;
            } else {
              return true;
            }
            //
          },
          render: (h, params) => {
            return h("span", params.row.offsetVal ? params.row.offsetVal : 0);
          },
        },
        {
          label: "PT变比",
          prop: "pt",
          isShow: (row) => {
            return (this.formData.mesaType == "201" ||
              this.formData.mesaType == "202") && this.isSysEnergyType;
          }
        },
        {
          label: "CT变比",
          prop: "ct",
          isShow: (row) => {
            return (this.formData.mesaType == "201" ||
              this.formData.mesaType == "202") && this.isSysEnergyType;
          }
        },
        {
          label: "量测值字典",
          prop: "meterValueDesc",
          isShow: (row) => {
            return (this.formData.mesaType == "201" ||
              this.formData.mesaType == "202") && this.isSysEnergyType;
          }
        },
        {
          label: "关联类型",
          prop: "associationType",
          render: (h, params) => {
            let name = null;
            this.nitBusTypeDict.map((item) => {
              if (item.dictActualValue == params.row.relatedDevType) {
                name = item.dictName;
              }
            });
            return h("span", name);
          },
        },
        {
          label: "关联对象",
          prop: "relatedDevName",
        },

        // {
        //     label: '量测类型',
        //     prop: 'measureType',
        //     render: (h, params) => {
        //         let name = null
        //         this.measureTypeList.map((item) => {
        //             if (item.dictActualValue == params.row.mesaType) {
        //                 name = item.dictName
        //             }
        //         })
        //         return h('span', name);
        //     },
        // },
        {
          label: "历史数据",
          prop: "showHistory",
          width: 100,
          isShow: (row) => {
            if (
              this.formData.mesaType == "203" ||
              this.formData.mesaType == "204"
            ) {
              return false;
            } else {
              return true;
            }
          },
          labelrender: (h, { column, $index }) => {
            return h("span", {}, [
              h('el-checkbox', {
                attrs: {
                  value: this.radioObj
                },
                props: {
                },
                on: {
                  change: (val) => {
                    let a = []
                    this.radioObj = val
                    this.dataSource.map((item) => {
                      item.showHistory = val
                      a.push(item.meterId)
                    })
                    this.batchUpdateMeterShowHistory(a, val ? 1 : 0)
                    // this.getAllSheetData().then(data => {
                    //   this.dataSourceBAK.map((item) => {
                    //     a.push(item.meterId)
                    //   })
                    //   this.batchUpdateMeterShowHistory(a, val ? 1 : 0)
                    // })
                  }
                },
              }),
              h("el-tooltip", {
                class: "header-icon",
                props: {
                  effect: "dark",
                  content: "勾选后，此项量测将在历史数据中存储全部通道的所有变化数据，数据密度大，会占用系统性能，请按需筛选",
                  placement: "top-start"
                },
              }, [
                h('i', {
                  class: "el-icon-question",
                  style: "margin: 0 5px"
                }, ''),
              ]),
              h("span", {}, column.label)
            ]);
          },
          render: (h, params) => {
            return h('el-checkbox', {
              attrs: {
                value: params.row.showHistory == 1 ? true : false,
              },
              props: {},
              on: {
                change: (val) => {
                  params.row.showHistory = val;
                  this.batchUpdateMeterShowHistory([params.row.meterId], val ? 1 : 0)
                },
              },
            });
          },
        },
        {
          label: "通道组",
          prop: "channelGroupName",
        },
        // {
        //   label: "适用通道",
        //   prop: "adaptChannelName",
        // },
      ],
      batchColumns: [
        {
          label: "序号",
          prop: "ranking",
          width: "70px",
          render: (h, params) => {
            return h("span", params.index + 1);
          },
        },
        // {

        //     label: '量测类型',
        //     prop: 'relatedName',
        //     width: '180px',
        //     labelrender: (h, { column, $index }) => {
        //         return h('span', { class: 'header-icon' }, [h('span', {}, '*'), h('span', {}, column.label)])
        //     },
        //     render: (h, params) => {
        //         return h(nuRadioButton, {
        //             attrs: {
        //                 value: params.row.relatedName,
        //                 group: this.measureTypeGroup,
        //                 size: "mini"
        //             },
        //             props: {},
        //             style: 'display:flex;margin:0 5px;width:100%',
        //             on: {
        //                 input: val => {
        //                     params.row.relatedName = val
        //                     this.measureTypeList.map((item) => {
        //                         if (item.dictName == val) {
        //                             params.row.mesaType = item.dictActualValue
        //                         }
        //                     })
        //                     if (val == '遥信') {
        //                         params.row.coeff = ''
        //                         params.row.upperLimit = ''
        //                         params.row.unitName = ''
        //                         params.row.lowerLimit = ''
        //                     } else {
        //                         params.row.coeff = '1.00'
        //                         params.row.unitName = 'MW'
        //                     }
        //                 }
        //             },
        //         });
        //     },
        // },
        {
          label: "量测点号",
          prop: "ioa",
          labelrender: (h, { column, $index }) => {
            return h("span", { class: "header-icon" }, [
              h("span", {}, "*"),
              h("span", {}, column.label),
            ]);
          },
          render: (h, params) => {
            return h(nuInput, {
              attrs: {
                value: params.row.ioa,
                placeholder: "请输入数字",
                type: "text",
              },
              props: {
                size: "middle",
              },

              on: {
                input: (val) => {
                  if (!isNaN(val)) {
                    params.row.ioa = val;
                  }
                },
              },
            });
          },
        },
        {
          label: "关联对象",
          prop: "unitBusType",
          width: "300px",
          labelrender: (h, { column, $index }) => {
            return h("span", { class: "header-icon" }, [
              h("span", {}, "*"),
              h("span", {}, column.label),
            ]);
          },
          render: (h, params) => {
            return h("div", { class: "unitBusTypeBox" }, [
              h(nuSelect, {
                attrs: {
                  value: params.row.relatedDevType,
                  placeholder: "请选择",
                  autocomplete: "off",
                  type: "text",
                },
                props: {
                  list: this.unitBusTypeList,
                  valueName: "dictActualValue",
                  label: "dictName",
                },
                style: "display:flex;margin:0 5px",
                class: "searchSelect",
                on: {
                  change: (val) => {
                    params.row.relatedDevType = val;
                    params.row.measuringName = this.unitBusTypeChange(val);
                    params.row.relatedDevId = "";
                    params.row.meterName = "";
                  },
                },
              }),
              h(nuSelect, {
                attrs: {
                  value: params.row.relatedDevId,
                  placeholder: "请选择",
                  autocomplete: "off",
                  type: "text",
                },
                props: {
                  list: (() =>
                    this.setRelatedDevType(params.row.relatedDevType))(),
                  valueName: (() =>
                    this.setValueName(params.row.relatedDevType))(),
                  label: (() => this.setlableList(params.row.relatedDevType))(),
                },
                style: "width:140px;margin:0 5px",
                class: "searchSelect",
                on: {
                  change: (val) => {
                    params.row.relatedDevId = val;
                    this.setRelatedDevType(params.row.relatedDevType).forEach(item => {
                      if (item.phyunitId && item.phyunitId == val) {
                        params.row.relatedDevName = item.phyunitName;
                      }
                      if (item.busId && item.busId == val) {
                        params.row.relatedDevName = item.busName;
                      }
                      if (item.deviceId && item.deviceId == val) {
                        params.row.relatedDevName = item.deviceName;
                      }
                    })
                  },
                },
              }),
            ]);
          },
        },
        {
          label: "对应量测名称",
          prop: "meterName",
          labelrender: (h, { column, $index }) => {
            return h("span", { class: "header-icon" }, [
              h("span", {}, "*"),
              h("span", {}, column.label),
            ]);
          },
          render: (h, params) => {
            return h(
              "el-select",
              {
                attrs: {
                  value: params.row.meterName,
                  placeholder: "请选择",
                  autocomplete: "off",
                  type: "text",
                  clearable: true,
                },
                props: {},
                style: "width:100%",
                on: {
                  change: (val) => {
                    params.row.meterName = val;
                  },
                },
              },
              (() =>
                this.restaurantsType(params.row.measuringName))().map((item) => {
                  return h("el-option", {
                    props: {
                      value: item.dictName,
                      label: item.dictName,
                    },
                  });
                })
            );
          },
        },
        {
          label: "单位",
          prop: "unit",
          labelrender: (h, { column, $index }) => {
            if (this.formData.mesaType == "203") {
              return h("span", { class: "header-icon" }, [
                h("span", {}),
                h("span", {}, column.label),
              ]);
            } else {
              return h("span", { class: "header-icon" }, [
                h("span", {}, "*"),
                h("span", {}, column.label),
              ]);
            }
          },
          render: (h, params) => {
            if (params.row.mesaType == "201" || params.row.mesaType == "203") {
              //
              return h(nuSelect, {
                attrs: {
                  value: params.row.unit,
                  placeholder: "请选择",
                  autocomplete: "off",
                  type: "text",
                  disabled: false,
                  clearable: true,
                },
                props: {
                  list: this.unitList,
                  valueName: "dictName",
                  label: "dictName",
                },
                style: "width:100%",
                class: "searchSelect",
                on: {
                  change: (val) => {
                    params.row.unit = val;
                  },
                },
              });
            }
          },
        },
        {
          label: "系数",
          prop: "coeff",
          labelrender: (h, { column, $index }) => {
            if (this.formData.mesaType == "203") {
              return h("span", { class: "header-icon" }, [
                h("span", {}),
                h("span", {}, column.label),
              ]);
            } else {
              return h("span", { class: "header-icon" }, [
                h("span", {}, "*"),
                h("span", {}, column.label),
              ]);
            }
          },
          render: (h, params) => {
            if (params.row.mesaType == "201" || params.row.mesaType == "203") {
              return h(nuInput, {
                attrs: {
                  value: params.row.coeff,
                  placeholder: "请输入",
                  type: "text",
                },
                props: {
                  size: "middle",
                },
                style: "width:100%",
                on: {
                  input: (val) => {
                    params.row.coeff = val;
                    if (val.indexOf(".") > 0) {
                      params.row.coeff = val.slice(0, val.indexOf(".") + 11);
                    }
                  },
                  blur: ($event) => this.coefBlur($event, 2),
                },
              });
            }
          },
        },
        {
          label: "偏移量",
          prop: "offsetVal",
          labelrender: (h, { column, $index }) => {
            if (this.formData.mesaType == "203") {
              return h("span", { class: "header-icon" }, [
                h("span", {}),
                h("span", {}, column.label),
              ]);
            } else {
              return h("span", { class: "header-icon" }, [
                h("span", {}, "*"),
                h("span", {}, column.label),
              ]);
            }
          },
          render: (h, params) => {
            if (params.row.mesaType == "201" || params.row.mesaType == "203") {
              //
              return h(nuInput, {
                attrs: {
                  value: params.row.offsetVal,
                  placeholder: "请输入",
                  type: "number",
                },
                props: {
                  size: "middle",
                },
                style: "width:100%",
                on: {
                  input: (val) => {
                    params.row.offsetVal = val;
                  },
                },
              });
            }
          },
        },
        {
          label: "上限",
          prop: "upperLimit",
          render: (h, params) => {
            if (params.row.mesaType == "201" || params.row.mesaType == "203") {
              return h(nuInput, {
                attrs: {
                  value: params.row.upperLimit,
                  placeholder: "请输入",
                  type: "number",
                },
                props: {
                  size: "middle",
                },
                style: "width:100%",
                on: {
                  input: (val) => {
                    params.row.upperLimit = val;
                  },
                },
              });
            }
          },
        },
        {
          label: "下限",
          prop: "lowerLimit",
          render: (h, params) => {
            if (params.row.mesaType == "201" || params.row.mesaType == "203") {
              return h(nuInput, {
                attrs: {
                  value: params.row.lowerLimit,
                  placeholder: "请输入",
                  type: "number",
                },
                props: {
                  size: "middle",
                },
                style: "width:100%",
                on: {
                  input: (val) => {
                    params.row.lowerLimit = val;
                  },
                },
              });
            }
          },
        },
      ],
      dataSource: [{}],
      dataSourceBAK: [{}],
      batchDataSource: [{}],
      options: {
        "default-expand-all": true,
        "element-loading-background": "rgba(225,239,242)",
        "element-loading-text": "数据正在加载中",
        "row-key": "pid",
        "header-cell-style": {
          background: "rgba(105, 159, 209, 0.7)",
          color: "#fff",
          fontWeight: "bold",
          fontsize: "16px",
        },
        height: "calc(100vh - 400px)",
        isNoTableHeight: true,
        props: {
          // fixed: 'right'
        },
        defaultSort: { prop: 'ioa', order: 'ascending' }
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_SCADA + window.api.meterExcelFileImport,
        // 上传时附带的额外参数
        data: {},
        fileList: []
      },
      state: "",
      timeout: null,
      restaurants: {},
      measuringName: "", // 请求量测的参数
      transformerMap: {}, // 全部关联对象
      selectRadioValue: ""
    };
  },
  computed: {
    dialogFormDisabled() { },
    setRelatedDevType() {
      return function (key) {
        return this.transformerMap[key];
      };
    },
    restaurantsType() {
      return function (key) {
        return this.restaurants[key] || [];
      };
    },
    setValueName() {
      return function (key) {
        let obj = {
          301: "phyunitId",
          302: "busId",
        };
        return obj[key] ? obj[key] : "deviceId";
      };
    },
    setlableList() {
      return function (key) {
        let obj = {
          301: "phyunitName",
          302: "busName",
        };
        return obj[key] ? obj[key] : "deviceName";
      };
    },
    isMeasureType() {
      return (
        this.dialogFormData.mesaType == "201" ||
        this.dialogFormData.mesaType == "203"
      );
    },
    requiredFunc() {
      return (
        this.dialogFormData.mesaType == "202" ||
        this.dialogFormData.mesaType == "201"
      );
    },
    isSysEnergyType() {
      return store && store.getters.sysEnergyType == 'WIND'
    }
  },
  created() { },

  mounted() {
    // this.getMeasurationInfoSheet();
    // this.restaurants = this.loadAll();
    this.getChannelCondition();
    // this.getMesaNames()
    this.getCrewManageTableDataList();
    this.getMesaTypes();
    this.getRelatedDeviceTypes();
    this.getOneLevelDicts();
  },
  methods: {
    /**
     * 查询
     */
    searchTable() {
      this.$refs["formData"].searchForm("form");
    },
    sortChange(column, prop, order) {
      if (column.order == 'ascending') {
        this.ioaOrder = 'asc'
      } else if (column.order == 'descending') {
        this.ioaOrder = 'desc'
      }
      this.getMeasurationInfoSheetData();
    },
    // 数组按照某个字段进行排序
    sortTableArr(arr) {
      for (var i = 0; i < arr.length - 1; i++) {
        for (var j = 0; j < arr.length - i - 1; j++) {
          if (arr[j].ioa > arr[j + 1].ioa) {
            // 相邻元素两两对比
            var hand = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = hand;
          }
        }
      }
      return arr;
    },
    /**
     * 获取量测类型下拉选项
     */
    getMesaTypes() {
      this.$httpGet(window.api.getMesaTypes)
        .then((res) => {
          if (res.code == 200) {
            this.measureTypeList = res.data;
          }
        })
        .catch((err) => { });
    },
    /**
     * 获取关联设备类型下拉框
     */
    getRelatedDeviceTypes() {
      this.$httpGet(window.api.getRelatedDeviceTypes)
        .then((res) => {
          if (res.code == 200) {
            this.unitBusTypeList = res.data;
            this.getAssociatedObjects();

          }
        })
        .catch((err) => { });
    },

    getAssociatedObjects() {
      this.unitBusTypeList.forEach((tiem) => {

        this.getMultiLevelDictByName(tiem.dictEnName)
        if (tiem.dictActualValue == "301") {
          return
        } else if (tiem.dictActualValue == "302") {
          // 关联母线
          let postData = {
            busName: "",
            ...this.pagination,
          };
          this.$httpGet(window.api.getBusManageTableData, postData)
            .then((res) => {
              if (res.code == 200 && res.rows) {
                this.busNameList = res.rows;
                this.transformerMap[tiem.dictActualValue] = res.rows
              } else {
              }
            })
            .catch((err) => { });
        } else {
          let postData = {
            deviceType: tiem.dictActualValue,
            pageSize: 99999,
            pageNum: 1,
          };

          this.$httpGet(window.api.getDevices, postData)
            .then((res) => {
              if (res.code == 200 && res.rows) {
                this.transformerMap[tiem.dictActualValue] = res.rows
              } else {
              }
            })
            .catch((err) => { });
        }
      });
    },

    /**
     * 获取量测名称下拉列表
     */
    // getMesaNames() {
    //     this.$httpGet(window.api.getMesaNames).then(res => {
    //         if (res.code == 200) {

    //             this.restaurants = res.data
    //         }
    //     }).catch(err => {

    //     });
    // },
    /**
     * form组件内置查询事件
     */
    searchForm(val) {
      if (val) {
        this.getMeasurationInfoSheetData();
      }
    },
    /**
     * 清除数据
     */
    clearParams() {
      this.formData.devName = "";
      this.formData.devType = "";
      this.formData.meterName = "";
    },
    /**
     * 量测类型change
     */
    measureTypeChange() { },
    /**
     * 关联类型change
     */
    associationTypeChange() { },
    /**
     * 关联机组类型
     */

    getOneLevelDicts() {
      this.$httpGet(window.api.getOneLevelDicts, {
        dictType: "RELATED_DEVICE_TYPE",
        pageSize: 9999,
        pageNum: 1,
      })
        .then((res) => {
          if (res.code == 200) {
            this.nitBusTypeDict = res.rows;
          } else {
          }
        })
        .catch((err) => { });
      this.$httpGet(window.api.getOneLevelDicts, {
        dictType: "MEASUREMENT_UNIT",
        pageSize: 9999,
        pageNum: 1,
      })
        .then((res) => {
          if (res.code == 200) {
            this.unitList = res.rows;
          } else {
          }
        })
        .catch((err) => { });
    },

    getCrewManageTableDataList() {
      // 关联机组
      let postData = {
        // ...this.formData,
        ...this.pagination,
        phyunitName: "",
      };
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.$httpGet(window.api.getCrewManageTableData, postData)
        .then((res) => {
          if (res.code == 200 && res.rows) {
            this.unitNameList = res.rows;
            this.transformerMap["301"] = res.rows;
          } else {
          }
        })
        .catch((err) => { });
    },
    /**
     * 关联机组母线change
     */
    unitBusTypeChange(val) {
      this.nitBusTypeDict.map((res) => {
        if (res.dictActualValue == val) {
          this.measuringName = res.dictEnName
          //   this.getMultiLevelDictByName(res.dictEnName);
        }
        this.selectRadioValue = val
      });
      this.dialogFormData.relatedDevType = val
      this.dialogFormData.relatedDevId = "";
      this.dialogFormData.meterName = ""
      return this.measuringName
    },

    getMultiLevelDictByName(value) {

      // this.restaurants = {};
      this.$httpGet(window.api.getMultiLevelDictByName, { dictEnName: value })
        .then((res) => {
          if (res.code == 200 && res.rows) {
            let data = res.rows.filter((item) =>
              item.dictEnName != value
            );

            this.restaurants[value] = data
          } else {
          }
        })
        .catch((err) => { });
    },

    /**
     * 通道组change
     */
    channelChange(val) {
      this.channelGroupObject.map((item) => {
        if (item.id == val) {
          // this.dialogFormData.relatedDevId = item.plantId
          this.dialogFormData.channelGroupName = item.groupName;
          this.dialogFormData.relatedDevName = item.plantName;
          this.dialogFormData.channelGroupId = item.id;
        }
      });
      this.formData.channel = val;
      this.searchTable();
    },
    /**
     * 获取通道组列表
     */
    getChannelCondition() {
      let postData = {
        pageNum: 1,
        pageSize: 99999,
        channelName: "",
      };
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.dataSource = [];

      this.$httpGet(window.api.getChannelGroupSet, postData)
        .then((res) => {
          if (res.code == 200 && res.rows) {
            this.channelGroupObject = res.rows;

            this.formData.channel = this.channelGroupObject[0].id;
            this.dialogFormData.channelGroupName =
              this.channelGroupObject[0].groupName;
            this.dialogFormData.relatedDevName =
              this.channelGroupObject[0].plantName;
            this.dialogFormData.channelGroupId = this.channelGroupObject[0].id;
            this.getMeasurationInfoSheetData();
          } else {
          }
        })
        .catch((err) => { });
    },
    /**
     * 系数验证小数点4位，不足补齐0
     * @param {*} e
     * @param {*} n
     */
    coefBlur(e, n) {
      n = n ? parseInt(n) : 0;
      if (n <= 0) {
        return Math.round(e.target.value);
      }
      //   e.target.value =
      //     Math.round(e.target.value * Math.pow(10, n)) / Math.pow(10, n); //四舍五入
      //   e.target.value = Number(e.target.value).toFixed(n); //补足位数
    },
    related(val) {
      this.measureTypeList.map((item) => {
        if (item.dictName == val) {
          this.dialogFormData.mesaType = item.dictActualValue;
          return item.dictActualValue;
        }
      });
    },
    /**
     * 新增
     */
    addTable() {
      this.dialogTitle = "新增";
      this.dialogShow = true;
      if (this.formData.mesaType == 203) {
        this.dialogFormData.unit = "";
      }
      // this.dialogFormData.meterName = ""
      // this.dialogFormData.relatedDevType = ""
      //   this.restaurants = {};
      //   this.busNameList = [];
      //   this.transformerList = [];
      // this.dialogFormData.relatedDevId = ""
    },
    // 选中关联
    searchSelectChange(val) {

      this.setRelatedDevType(this.selectRadioValue).forEach(item => {
        if (item.phyunitId && item.phyunitId == val) {
          this.dialogFormData.relatedDevName = item.phyunitName;
        }
        if (item.busId && item.busId == val) {
          this.dialogFormData.relatedDevName = item.busName;
        }
        if (item.deviceId && item.deviceId == val) {
          this.dialogFormData.relatedDevName = item.deviceName;
        }
      })
      //   
      //   this.unitNameList.map((item) => {
      //     if (item.phyunitId == val) {
      //       this.dialogFormData.relatedDevName = item.phyunitName;
      //     }
      //   });
      //   this.busNameList.map((item) => {
      //     if (item.busId == val) {
      //       this.dialogFormData.relatedDevName = item.busName;
      //     }
      //   });
      //   this.transformerList.map((item) => {
      //     if (item.deviceId == val) {
      //       this.dialogFormData.relatedDevName = item.deviceName;
      //     }
      //   });
    },
    /**
     * 关联input
     */
    relatedNameInput(val) {
      this.radioObj = false
      this.dialogFormData.mesaType = val;
      let p = JSON.parse(JSON.stringify(this.pagination))
      this.pagination = null
      this.$nextTick(() => {
        p.pageNum = 1;
        p.currentPage = 1;
        this.pagination = p
        this.getMeasurationInfoSheetData();
      })
    },
    /**
     * 批量新增
     */
    batchAddTable() {
      this.dialogBatchShow = true;
      this.dialogBatchTitle = "批量新增";
      //   this.restaurants = [];
      //   this.busNameList = [];
      //   this.transformerList = [];
      this.batchDataSource = this.generateCycleData();
    },
    /** 下载模板操作 */
    importTemplate() {
      const h = this.$createElement;
      this.$msgbox({
        title: '提示',
        message: h('div', null, [
          h('p', { width: '500px' }, '1、下载模板前，请确认已维护好通道工况和设备管理信息哦！下载的模板根据已维护的信息动态生成！'),
          h('p', { width: '500px' }, '2、一次性最多导入500条数据，若数据量大，请分多个excel导入。')
        ]),
        showCancelButton: true,
        confirmButtonText: '确定继续下载',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonText = '执行中...';
            axios
              .get(process.env.VUE_APP_BASE_SCADA + window.api.downLoadMeterImportTemplate, {
                responseType: "blob",
              })
              .then((response) => {
                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement("a");
                let fname = "导入模板.xls";
                link.href = url;
                link.setAttribute("download", fname);
                document.body.appendChild(link);
                link.click();
                done();
                setTimeout(() => {
                  instance.confirmButtonLoading = false;
                }, 300);
              })
              .catch((error) => { });
          } else {
            done();
          }
        }
      }).then(action => {

      });
      // this.getDownload(window.api.exportRealTelemetrys, {
      //   ...this.formData
      // }, `导入模板.xlsx`)
      // this.download('system/user/importTemplate', {
      // }, `user_template_${new Date().getTime()}.xlsx`)

    },
    /**
     * 导入
     */
    importTable() {
      this.upload.title = "导入";
      this.upload.open = true;
      document.getElementsByTagName("body")[0].className = "upload-body";
    },
    /**
     * 导出
     */
    exportTable() {
      let postData = {
        ...this.formData,
        channelGroupId: this.formData.channel
      };
      axios
        .get(process.env.VUE_APP_BASE_SCADA + window.api.downLoadMeterExportFile, {
          responseType: "blob",
          params: postData,
        })
        .then((response) => {
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement("a");
          let fname = "量测信息表数据.xlsx";
          link.href = url;
          link.setAttribute("download", fname);
          document.body.appendChild(link);
          link.click();
        })
        .catch((error) => {
          console.log("error:" + JSON.stringify(error));
        });
    },
    /**
     * 每页条数变化事件
     */
    handleSizeChange(val) {
      this.pagination.pageNum = 1;
      this.pagination.pageSize = val;
      this.getMeasurationInfoSheetData();
    },
    /**
     * 改变分页触发事件
     */
    handleChangePage(val) {
      this.pagination.pageNum = val;
      this.getMeasurationInfoSheetData();
    },
    /**
     * 返回输入建议的方法
     * @param {*} queryString
     * @param {*} cb
     */
    querySearchAsync(queryString, cb) {
      var restaurants = this.restaurantsType(this.measuringName);
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 0 * Math.random());
    },
    /**
     * 过滤数据
     * @param {*} queryString
     */
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.dictName.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    /**
     * 点击选中建议项时触发
     * @param {*} item
     */
    handleSelect(item) {
      this.dialogFormData.meterName = item.dictName;
    },
    /**
     * 表格-编辑
     */
    openEdit(row) {
      this.dialogTitle = "编辑";
      row["oldRelatedDevId"] = row.relatedDevId;
      // row.relatedDevId = row.relatedDevName;

      this.nitBusTypeDict.map((res) => {
        if (res.dictActualValue == row.relatedDevType) {
          this.measuringName = res.dictEnName
        }
      });
      // this.measuringName = row.relatedDevType
      Object.assign(this.dialogFormData, row);
      this.dialogFormData.isStatistics = row.isStatistics == 1 ? "是" : "否";
      this.dialogShow = true;
    },
    /**
     * 表格-详情
     */
    openDetail(row) {
      this.dialogTitle = "详情";
      Object.assign(this.dialogFormData, row);
      this.dialogShow = true;
    },
    /**
     * 表格-禁用
     */
    forbidden(row) {
      // 禁用状态下调用重启
      if (row.isStatistics == 0) {
        this.$confirm("是否重新启用该电度量配置?", "确认重启", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            // this.forbiddenMeteringPointTableData(row)
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消重启",
            });
          });
        //
      } else if (row.isStatistics == 1) {
        this.$confirm("是否禁用该电度量?", "确认禁用", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            // this.forbiddenMeteringPointTableData(row)
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消禁用",
            });
          });
      }
    },
    /**
     * 动态生成批量新增数据
     */
    generateCycleData() {
      let data = [];
      Array.from({ length: 10 }).forEach((item, i) => {
        data.push({
          unitBusType: "关联机组",
          meterName: "",
          // unitBusName: '',
          mesaType: this.formData.mesaType,
          channelGroupId: this.dialogFormData.channelGroupId,
          channelGroupName: this.dialogFormData.channelGroupName,
          relatedDevId: "",
          relatedDevName: this.dialogFormData.relatedDevName,
          upperLimit: "",
          lowerLimit: "",
          coeff: "1.00",
          unit: this.formData.mesaType == 203 ? "" : "MW",
          ioa: "",
          relatedName: "遥测",
          relatedDevType: "",
          measuringName: "",
          offsetVal: ""
        });
      });
      return data;
    },
    /**
     * 表格-删除
     */
    tbRowdetele(row) {
      this.$confirm("确定要删除该量测点吗？", "确认删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.delMeasurationInfoSheet(row);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /**
     * dialogFormData组件内置提交事件
     */
    diaSubmitForm(val) {
      if (val) {
        if (this.dialogTitle == "编辑") {
          this.editMeasurationInfoSheetData();
        } else if (this.dialogTitle == "新增") {
          this.addMeasurationInfoSheetData();
        }
      }
    },
    /**
     * 弹窗-单点新增-保存
     */
    diaSave() {
      this.$refs["dialogFormData"].submitForm("form");

      // this.$refs['formData'].clearValidate('form');
      // this.$refs['dialogFormData'].clearValidate('form');
    },
    /**
     * 弹窗-单点新增-关闭
     */
    diaClose() {
      this.dialogShow = false;
      this.measuringName = ""
      this.dialogFormData = {
        unitBusType: "关联机组",
        meterName: "",
        // unitBusName: '',
        mesaType: this.formData.mesaType,
        channelGroupId: this.dialogFormData.channelGroupId,
        channelGroupName: this.dialogFormData.channelGroupName,
        relatedDevId: "",
        relatedDevName: this.dialogFormData.relatedDevName,
        upperLimit: "",
        lowerLimit: "",
        coeff: "",
        unit: "MW",
        ioa: "",
        relatedName: "遥测",
        relatedDevType: "",
        offsetVal: "",
        pt: "",
        ct: "",
        meterValueDesc: ""
      };
      // this.$refs['formData'].clearValidate('form');
      this.$refs["dialogFormData"].clearValidate("form");
    },
    /**
     * 重置表单
     */
    resetForm(formName) {
      this.$refs[formName].resetForm("form");
      for (let k in this[formName]) {
        if (
          Object.prototype.toString.call(this[formName][k]) == "[object String]"
        ) {
          this[formName][k] = "";
        } else if (
          Object.prototype.toString.call(this[formName][k]) == "[object Array]"
        ) {
          this[formName][k] = [];
        } else if (
          Object.prototype.toString.call(this[formName][k]) == "[object Number]"
        ) {
          this[formName][k] = "";
        }
      }
    },
    /**
     * 弹窗-批量新增-保存
     */
    diaBatchSave() {
      let data = [];
      let pass = true;
      this.batchDataSource.forEach((item) => {
        let flag = false;
        for (let k in item) {
          if (
            k != "relatedName" &&
            k != "unit" &&
            k != "unitBusType" &&
            k != "coeff" &&
            k != "upperLimit" &&
            k != "lowerLimit" &&
            k != "channelGroupId" &&
            k != "channelGroupName" &&
            k != "mesaType" &&
            k != "relatedDevName" &&
            k != "offsetVal"
          ) {
            if (item[k]) {
              flag = true;
            }
          }
        }
        if (flag) {
          let complete = true;
          for (let k in item) {
            if (item["mesaType"] == "203") {
              if (!item[k]) {
                if (k != "upperLimit" && k != "lowerLimit" && k != "coeff" && k != "unit" && k != "offsetVal") {
                  complete = false;
                }
              }
            }
            else {
              if (!item[k]) {
                if (item["mesaType"] == "203") {
                  if (k != "upperLimit" && k != "lowerLimit" && k != "coeff" && k != "unit" && k != "offsetVal") {
                    complete = false;
                  }
                } else if (item["mesaType"] == "201") {
                  if (k != "upperLimit" && k != "lowerLimit") {
                    complete = false;
                  }
                } else {
                  if (
                    k != "upperLimit" &&
                    k != "lowerLimit" &&
                    k != "coeff" &&
                    k != "unit" &&
                    k != "offsetVal"
                  ) {
                    complete = false;
                  }
                }
              }
            }
          }
          if (complete) {
            data.push(item);
          } else {
            pass = false;
          }
        }
      });

      if (pass) {
        if (!data.length) {
          this.$message({
            message: "请先配置信息",
            type: "info",
          });
          return false;
        }
        this.batchAddMeasurationInfoSheetData(data);
      } else {
        this.$message({
          message: "请将信息输入完整",
          type: "info",
        });
      }
    },
    /**
     * 弹窗-批量新增-关闭
     */
    diaBatchClose() {
      this.dialogBatchShow = false;
    },
    /**
     * 获取表格数据
     */
    getMeasurationInfoSheetData() {
      let postData = {
        ...this.formData,
        ...this.pagination,
        channelGroupId: this.dialogFormData.channelGroupId,
        ioaOrder: this.ioaOrder

        // devName:"",
        // meterName:"",
        // mesaType:12,
        // devType:1
      };
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.$httpGet(window.api.getMeasurationInfoSheet, postData)
        .then((res) => {
          if (res.code) {
            this.dataSource = this.sortTableArr(res.rows);
            this.radioObj = true
            this.dataSource.forEach(item => {
              if (item.showHistory != 1) {
                this.radioObj = false
              }
            })
            this.pagination.total = res.total;
          } else {
          }
        })
        .catch((err) => { });
    },
    getAllSheetData() {
      let postData = {
        ...this.formData,
        pageSize: 9999,
        total: 0,
        pageNum: 1,
        channelGroupId: this.dialogFormData.channelGroupId,
      };
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      return new Promise((resolve, reject) => {
        this.$httpGet(window.api.getMeasurationInfoSheet, postData)
          .then((res) => {
            if (res.code) {
              this.dataSourceBAK = this.sortTableArr(res.rows);
              resolve(this.dataSourceBAK)
            } else {
            }
          })
          .catch((err) => { });
      })
    },
    getSheetData(postData) {

    },
    /**
     * 单选
     */
    handleCurrentChange(val) {
      this.currentRow = val;
      //
    },
    /**
     * 复制
     */
    copyRow() {
      // this.dataSource.push(this.currentRow)
    },
    /**
     * 粘贴
     */
    stickRow() { },
    /**
     * 编辑接口
     */
    editMeasurationInfoSheetData() {
      let postData = {
        ...this.dialogFormData,
      };
      // relatedDevId: this.dialogFormData.relatedDevId,
      //         relatedDevName: this.dialogFormData.relatedDevName,
      if (postData.relatedDevId == postData.relatedDevName) {
        postData.relatedDevId == postData.oldRelatedDevId;
      }
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.$httpPost(window.api.addMeasurationInfoSheet, postData)
        .then((res) => {
          if (res.code == 200) {
            if (res.count > 0) {
              this.$message({
                message: res.desc,
                type: "success",
              });
              this.diaClose();
              this.getMeasurationInfoSheetData();
            } else {
              this.$message({
                message: res.desc,
                type: "info",
              });
            }
          } else {
          }
        })
        .catch((err) => { });
    },
    /**
     * 删除表格数据
     */
    delMeasurationInfoSheet(row) {
      let postData = {
        meterId: row.meterId,
      };
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.$httpGet(window.api.deleteMeter, postData)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getMeasurationInfoSheetData();
          } else {
          }
        })
        .catch((err) => { });
    },
    /**
     * 新增接口
     */
    addMeasurationInfoSheetData() {
      let postData = {
        ...this.dialogFormData,
      };

      if (postData.relatedDevType == this.unitBusTypeList[0].dictName) {
        postData.relatedDevType = this.unitBusTypeList[0].dictActualValue;
      }
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.$httpPost(window.api.addMeasurationInfoSheet, postData)
        .then((res) => {
          if (res.code == 200) {
            if (res.count > 0) {
              this.$message({
                message: res.desc,
                type: "success",
              });
              this.diaClose();
              this.getMeasurationInfoSheetData();
            } else {
              this.$message({
                message: res.desc,
                type: "info",
              });
            }
          } else {
          }
        })
        .catch((err) => { });
    },
    /**
     * 批量新增接口
     */
    batchAddMeasurationInfoSheetData(data) {
      // let postData = {
      //     ...data,
      // };
      // for (let k in postData.query) {
      //     if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
      //         postData.query[k] = postData.query[k].toString().trim();
      //     }
      // }
      this.$httpPost(window.api.batchSaveMeters, data)
        .then((res) => {
          if (res.code == 200) {
            if (res.count > 0) {
              this.$message({
                message: res.desc,
                type: "success",
              });
              this.dialogBatchShow = false;
              this.getMeasurationInfoSheetData();
            } else {
              this.$message({
                message: "计量点不可重复",
                type: "info",
              });
            }
          } else {
          }
        })
        .catch((err) => { });
    },
    /**
     * 设置量测对象是否存储历史数据
     */
    batchUpdateMeterShowHistory(meterIds, showHistory) {
      let postData = {
        "meterIds": meterIds,
        "showHistory": showHistory //是否显示历史(1:显示,:不显示)
      }
      this.$httpPost(window.api.batchUpdateMeterShowHistory, postData)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: res.msg,
              type: "success",
            });
            this.getMeasurationInfoSheetData()
          } else { }
        })
        .catch((err) => { });
    },
    /**
     * 文件上传change事件
     * @param {*} file
     * @param {*} fileList
     * @param {*} scope
     */
    handleChange(file, fileList, scope) {
      let imgSize = Number(file.size / 1024 / 1024);
      if (imgSize > 5) {
        this.$message({
          title: "",
          message: "文件大小不能超过5MB，请重新上传。",
          type: "warning",
        });
        this.$refs.upload.clearFiles();
        return false;
      }
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.submitFileFormPrompt(response, file)
    },
    // 提交上传文件
    submitFileForm() {
      // this.$refs["upload"].clearFiles()
      // this.$nextTick(() => {
      //   this.$refs["upload"].handleStart(file.raw)
      //   this.$refs.upload.submit();
      //   done();
      // })
      this.upload.data['updateStatus'] = '1'
      this.$refs.upload.submit()
    },
    // 关闭上传文件弹框
    closeFileForm() {
      this.$refs.upload.clearFiles();
      this.upload.open = false;
      this.upload.isUploading = false;
      document.body.removeAttribute("class", "upload-body");
      this.searchTable();
    },
    /**
     * 上传文件后提示信息
     */
    submitFileFormPrompt(response, file) {
      if (response.code == 200) {
        let msgHt = null
        const h = this.$createElement;
        if (response.data.upLoadStatus == 1) {
          msgHt = h('div', null, [
            h('p', {}, '本次上传数据共' + response.data.total + '条，有' + response.data.updateNum + '条点表数据系统已经存在，是否继续上传并更新点表配置数据？'),
          ])
        } else {
          msgHt = h('div', null, [
            h('p', {}, [
              h('span', {}, '本次模板数据共' + response.data.total + '条，导入成功' + (response.data.insertNum + response.data.updateNum) + '条，失败' + response.data.errorNum + '条'),
              response.data.errorNum > 0 ? h(nuButton, {
                type: 'text',
                on: {
                  click: () => {
                    this.downLoadImportExcelErrorFile(response.data.errorId)
                  },
                },
              }, '导入失败详情下载') : ''
            ]),
            response.data.errorNum > 0 ? h('div', {}, [
              h('p', {}, '可能失败原因：'),
              h('p', {}, '1.填写名称与系统中配置名称不符；'),
              h('p', {}, '2.该条目必填项未填；'),
              h('p', {}, '3.该条目未按照规定格式填写。')
            ]) : ''
          ])
        }
        this.$msgbox({
          title: '提示',
          message: msgHt,
          showCancelButton: true,
          showConfirmButton: response.data.upLoadStatus == 1 ? true : false,
          confirmButtonText: '确定继续',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonText = '执行中...';
              this.upload.data['updateStatus'] = '2'
              this.$refs["upload"].clearFiles()
              this.$nextTick(() => {
                this.$refs["upload"].handleStart(file.raw)
                this.$refs.upload.submit();
              })
              done();
            } else {
              this.closeFileForm()
              done();
              this.importTable()
            }
          }
        }).then(action => {
        });
      } else {
        this.$message({
          message: response.msg,
          type: "info",
        });
      }
    },
    /**
     * 导出Excel错误信息文件
     */
    downLoadImportExcelErrorFile(id) {
      axios
        .get(process.env.VUE_APP_BASE_SCADA + window.api.downLoadImportExcelErrorFile + '?errorId=' + id, {
          responseType: "blob",
        })
        .then((response) => {
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement("a");
          let fname = "错误信息.txt";
          link.href = url;
          link.setAttribute("download", fname);
          document.body.appendChild(link);
          link.click();
        })
        .catch((error) => { });
    },
    /**
     * 下载txt
     * @param {} filename 
     * @param {*} text 
     */
    download(filename, text) {
      var element = document.createElement('a');
      element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
      element.setAttribute('download', filename);
      element.click();
    }
    // 远程搜索数据
    // loadAll() {
    //     this.$httpGet(window.api.getMesaNames).then(res => {
    //         if (res.code == 200) {

    //             return res.data
    //         }
    //     }).catch(err => {

    //     });
    //     // return [
    //     //     { "dddd": "三全鲜食（北新泾店）", "address": "长宁区新渔路144号" },
    //     //     { "value": "Hot honey 首尔炸鸡（仙霞路）", "address": "上海市长宁区淞虹路661号" },
    //     //     { "value": "新旺角茶餐厅", "address": "上海市普陀区真北路988号创邑金沙谷6号楼113" },
    //     //     { "value": "泷千家(天山西路店)", "address": "天山西路438号" },
    //     //     { "value": "胖仙女纸杯蛋糕（上海凌空店）", "address": "上海市长宁区金钟路968号1幢18号楼一层商铺18-101" },
    //     //     { "value": "贡茶", "address": "上海市长宁区金钟路633号" },
    //     //     { "value": "豪大大香鸡排超级奶爸", "address": "上海市嘉定区曹安公路曹安路1685号" },
    //     //     { "value": "茶芝兰（奶茶，手抓饼）", "address": "上海市普陀区同普路1435号" },
    //     //     { "value": "十二泷町", "address": "上海市北翟路1444弄81号B幢-107" },
    //     //     { "value": "星移浓缩咖啡", "address": "上海市嘉定区新郁路817号" },
    //     //     { "value": "阿姨奶茶/豪大大", "address": "嘉定区曹安路1611号" },
    //     //     { "value": "新麦甜四季甜品炸鸡", "address": "嘉定区曹安公路2383弄55号" },
    //     // ];
    // },
  },
};
</script>
<style></style>
<style scoped lang="scss">
.measurationInfoSheet {
  height: calc(100vh - 160px);
}

.searchForm {
  // height: calc(100% - 40px);
  display: flex;
  position: relative;
  padding: 0 10px;
  flex-wrap: wrap;
}

.radioStyle {
  margin: 20px 10px;
  display: flex;
}

.submitForm {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.btnBox {
  display: flex;
  // float: right;
  z-index: 10;
  position: absolute;
  top: 0;
  right: 0;
  align-items: center;
  margin: 7px 0 0 0;
}

.btnBox2 {
  display: flex;
  float: right;
  z-index: 10;
  position: absolute;
  top: 2px;
  right: 10px;
}

.upload_des {
  padding: 10px;

  ::v-deep .el-link--inner {
    font-size: 14px;
  }
}

.dialogHeaderSearch {
  background-color: var(--model-bgc);
  padding: 10px;
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  justify-content: right;

  &.batch {
    justify-content: center;

    .dialogSearchButton {
      margin: 10px 0;
    }
  }

  .el-form-item {
    margin-bottom: 4px;

    ::v-deep .el-form-item__error {
      padding-top: 0;
    }
  }
}

::v-deep .el-upload {
  width: 100%;

  .el-upload-dragger {
    width: auto;
  }
}

::v-deep .el-upload-list__item {
  padding: 0 14px;
}

::v-deep .el-radio-button__orig-radio:checked+.el-radio-button__inner {
  background-color: rgba(71, 99, 255, 1);
  border-color: rgba(71, 99, 255, 1);
}

::v-deep .unitBusTypeBox {
  display: flex;
}

::v-deep .el-table .el-input__inner {
  height: 28px !important;
  line-height: 28px !important;
}

::v-deep .header-icon {
  span:first-child {
    color: #ff4949;
    margin-right: 4px;
  }
}

.dialogHeaderSearch ::v-deep .el-table .el-table__cell {
  padding: 6px 0 !important;
}

.label {
  width: 130px;
  display: inline-block;
  text-align: right;
  vertical-align: middle;
  text-align: right;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  color: var(--input-color);
  line-height: 40px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
</style>